<template>
	<view class="post-detail-page">
		<!-- 导航栏 -->
		<up-navbar title="帖子详情" left-icon="arrow-left" @click-left="handleBack" background="#ffffff" border-bottom>
			<template #right>
				<up-icon name="more" size="20" color="#666666" @click="handleShare" class="nav-right-icon" />
			</template>
		</up-navbar>

		<!-- 全局加载状态 -->
		<up-loading-icon v-if="loading" class="page-loading" />

		<!-- 帖子主体内容 -->
		<view v-else class="post-container">
			<!-- 帖子作者信息 -->
			<view class="post-header">
				<!-- 作者头像：圆形图片 -->
				<!-- <up-image class="author-avatar" :src="post.avatar || defaultAvatar" circle mode="aspectFill"></up-image> -->
				<up-image :show-loading="true" :src="post.avatar || defaultAvatar" width="160rpx" height="160rpx"></up-image>

				<view class="author-info">
					<text class="author-name" @click="handleClickAuthor(post.userId)">
						{{ post.nickname ? post.nickname : '匿名用户' }}
					</text>
					<text class="post-time">{{ formatRelativeTime(post.createTime) || '未知时间' }}</text>
				</view>

				<!-- 关注按钮 -->
				<up-button size="small" @click="handleFollow">
					{{ isFollowed ? '已关注' : '关注' }}
				</up-button>
			</view>

			<!-- 帖子核心内容 -->
			<view class="post-content">
				<text class="post-title">{{ post.title || '无标题' }}</text>
				
				<!-- 板块标签 -->
				<view class="post-badges">
					<up-tag 
						v-if="post.subCategory" 
						:text="post.subCategory" 
						plain 
						size="mini" 
						type="primary"
					/>
					<up-tag v-if="post.isTop" text="置顶" type="error" size="mini" />
					<up-tag v-if="post.isEssence" text="精华" type="warning" size="mini" />
				</view>

				<text class="post-desc">{{ post.content || '无内容' }}</text>

				<!-- 帖子图片（多图预览） -->
				<view class="post-images" v-if="post.image && post.image.length">
					<up-album :urls="post.image" multipleSize="200rpx" space="30rpx"></up-album>
				</view>

				<!-- 交易区专属信息 -->
				<view class="trade-info" v-if="post.plateId === 3">
					<view class="info-section">
						<view class="info-title">商品信息</view>
						<view class="info-row">
							<text class="info-label">价格：</text>
							<text class="info-value price">¥{{ post.tradePrice }}</text>
						</view>
						<view class="info-row">
							<text class="info-label">成色：</text>
							<text class="info-value">{{ post.tradeCondition }}</text>
						</view>
						<view class="info-row">
							<text class="info-label">状态：</text>
							<up-tag 
								:text="getTradeStatusText(post.tradeStatus)" 
								:type="getTradeStatusType(post.tradeStatus)" 
								size="mini" 
							/>
						</view>
						<view class="info-row" v-if="post.contactInfo">
							<text class="info-label">联系方式：</text>
							<text class="info-value">{{ post.contactInfo }}</text>
						</view>
					</view>
					
					<!-- 联系卖家按钮 -->
					<up-button 
						v-if="post.tradeStatus === 'available'" 
						type="primary" 
						size="large" 
						@click="handleContact"
						color="#fa8c16"
						class="contact-btn"
					>
						联系卖家
					</up-button>
				</view>

				<!-- 求助区专属信息 -->
				<view class="help-info" v-if="post.plateId === 4">
					<view class="info-section">
						<view class="info-title">求助信息</view>
						<view class="info-row">
							<text class="info-label">状态：</text>
							<up-tag 
								:text="getHelpStatusText(post.helpStatus)" 
								:type="getHelpStatusType(post.helpStatus)" 
								size="mini" 
							/>
						</view>
						<view class="info-row" v-if="post.contactInfo">
							<text class="info-label">联系方式：</text>
							<text class="info-value">{{ post.contactInfo }}</text>
						</view>
					</view>
					
					<!-- 我来帮忙按钮 -->
					<up-button 
						v-if="post.helpStatus === 'pending'" 
						type="primary" 
						size="large" 
						@click="handleHelp"
						color="#722ed1"
						class="contact-btn"
					>
						我来帮忙
					</up-button>
				</view>

				<!-- 失物招领专属信息（已废弃，失物招领合并到求助区） -->
				<view class="lost-found-info" v-if="false">
					<view class="info-section">
						<view class="info-title">
							{{ post.subCategory === '寻物启事' ? '失物信息' : '拾物信息' }}
						</view>
						<view class="info-row" v-if="post.contactInfo">
							<text class="info-label">联系方式：</text>
							<text class="info-value">{{ post.contactInfo }}</text>
						</view>
					</view>
					
					<!-- 联系TA按钮 -->
					<up-button 
						type="primary" 
						size="large" 
						@click="handleContact"
						color="#13c2c2"
						class="contact-btn"
					>
						{{ post.subCategory === '寻物启事' ? '我捡到了' : '联系失主' }}
					</up-button>
				</view>

				<!-- 分享区附件下载 -->
				<view class="attachments" v-if="post.plateId === 2 && post.attachments && post.attachments.length">
					<view class="info-title">附件下载</view>
					<view class="attachment-list">
						<view 
							class="attachment-item" 
							v-for="(file, index) in post.attachments" 
							:key="index"
							@click="handleDownload(file)"
						>
							<up-icon name="file-text" size="20" color="#52c41a" />
							<view class="file-info">
								<text class="file-name">{{ file.name }}</text>
								<text class="file-size">{{ file.size }}</text>
							</view>
							<up-icon name="download" size="18" color="#999" />
						</view>
					</view>
				</view>
			</view>

			<!-- 帖子操作按钮 -->
			<view class="post-actions">
				<view class="action-item" @click="handleLike">
					<up-icon :name="isLiked ? 'heart-fill' : 'heart'" :color="isLiked ? '#ff4d4f' : '#0e1eff'" size="18"></up-icon>
					<text class="action-text" :style="{ color: isLiked ? '#ff4d4f' : '#0e1eff' }">
						{{ post.likeCount || 0 }}
					</text>
				</view>
				<view class="action-item" @click="handleCollect">
					<up-icon :name="isCollected ? 'star-fill' : 'star'" :color="isCollected ? '#ff9f1c' : '#0e1eff'" size="18"></up-icon>
					<text class="action-text" :style="{ color: isCollected ? '#ff9f1c' : '#0e1eff' }">
						{{ post.collectCount || 0 }}
					</text>
				</view>
				<view class="action-item">
					<up-icon name="eye" color="#666666" size="18"></up-icon>
					<text class="action-text">{{ post.viewCount || 0 }}</text>
				</view>
				<view class="action-item" @click="scrollToComment">
					<up-icon name="edit-pen" color="#666666" size="18"></up-icon>
					<text class="action-text">{{ post.commentCount || 0 }}</text>
				</view>
			</view>

			<!-- 评论区子组件 -->
			<CommentSection
				:comments="comments"
				:comment-count="post.commentCount"
				:default-avatar="defaultAvatar"
				:format-time="formatRelativeTime"
				:current-user="currentUser"
				:page="commentPage"
				:page-size="commentPageSize"
				:has-more="hasMoreComments"
				:comment-loading="commentLoading"
				@submitComment="handleSubmitComment"
				@submitReply="handleSubmitReply"
				@load-more="handleLoadMoreComments"
				@click-user="handleCommentUserClick"
				ref="commentComponent"
			/>
		</view>
	</view>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { onLoad } from '@dcloudio/uni-app';
import CommentSection from './components/commentSection.vue';
import { getPostService, getPostCommentsService } from '../../server/api/post';
import { parseImageStr } from '../../utils/imgsStr.js';
import { navigationUtils } from '../../utils/navigationUtils.js';
import {
	mockGetPost,
	mockGetComments,
	mockLikePost,
	mockUnlikePost,
	mockCollectPost,
	mockUncollectPost,
	mockPublishComment
} from '../../server/mock.js';
import showToast from '../../utils/showToast.js';

// 初始化实例
const router = useRouter();
const route = useRoute();
const commentComponent = ref(null);

// 响应式数据
const loading = ref(true);
const post = ref({});
const comments = ref([]);
const defaultAvatar = 'https://picsum.photos/200/200?random=1';
const commentPage = ref(1);
const commentPageSize = ref(10);
const hasMoreComments = ref(true);
const commentLoading = ref(false);
const currentUser = ref({
	userId: 10086,
	nickname: '当前登录用户',
	avatar: 'https://picsum.photos/200/200?random=888'
});
const isLiked = ref(false);
const isCollected = ref(false);
const isFollowed = ref(false);

// 页面加载
onLoad((option) => {
	const postId = option.postId;
	if (postId) {
		fetchPostDetail(postId);
		fetchComments(postId, commentPage.value, commentPageSize.value);
	} else {
		handleBack();
	}
});

// 请求帖子详情
const fetchPostDetail = async (postId) => {
	try {
		loading.value = true;
		
		// console.log(postId);
		const res = await getPostService({ postId: postId });
		
		post.value = res.data || {};
		post.value.image = parseImageStr(post.value.image);
		isLiked.value = false;
		isCollected.value = false;
		isFollowed.value = false;
	} catch (error) {
		console.error('获取帖子详情失败:', error);
	} finally {
		loading.value = false;
	}
};

// 分页请求评论
const fetchComments = async (postId, page, pageSize) => {
	try {
		commentLoading.value = true;
		const res = await getPostCommentsService(postId);
		const newComments = res.data || [];

		if (page === 1) {
			comments.value = newComments;
		} else {
			comments.value = [...comments.value, ...newComments];
		}

		hasMoreComments.value = newComments.length >= pageSize;
	} catch (error) {
		console.error('获取评论失败:', error);
	} finally {
		commentLoading.value = false;
	}
};

// 加载更多评论
const handleLoadMoreComments = () => {
	if (!hasMoreComments.value || commentLoading.value) return;
	commentPage.value += 1;
	fetchComments(post.value.postId, commentPage.value, commentPageSize.value);
};

// 跳转到用户信息页
const handleCommentUserClick = (userId) => {
	if (!userId) return;
	navigationUtils.openUserInfo(userId);
};

// 提交一级评论
const handleSubmitComment = async (commentData) => {
	try {
		const newComment = {
			commentId: Date.now(),
			postId: post.value.postId,
			userId: currentUser.value.userId,
			parentId: 0,
			nickname: currentUser.value.nickname,
			avatar: currentUser.value.avatar,
			content: commentData.content,
			createTime: Date.now(),
			status: 0
		};

		comments.value.unshift(newComment);
		post.value.commentCount = (post.value.commentCount || 0) + 1;
	} catch (error) {
		console.error('提交评论失败:', error);
	}
};

// 提交二级回复
const handleSubmitReply = async (replyData) => {
	try {
		const newReply = {
			commentId: Date.now(),
			postId: post.value.postId,
			userId: currentUser.value.userId,
			parentId: replyData.parentId,
			nickname: currentUser.value.nickname,
			avatar: currentUser.value.avatar,
			content: replyData.content,
			targetNickname: replyData.targetNickname,
			createTime: Date.now(),
			status: 0
		};

		const targetComment = comments.value.find((c) => c.commentId === replyData.parentId);
		if (targetComment) {
			if (!targetComment.replies) targetComment.replies = [];
			targetComment.replies.push(newReply);
			post.value.commentCount = (post.value.commentCount || 0) + 1;
		}
	} catch (error) {
		console.error('提交回复失败:', error);
	}
};

// 相对时间格式化
const formatRelativeTime = (timestamp) => {
	if (!timestamp) return '未知时间';
	const now = Date.now();
	const diff = (now - timestamp) / 1000;

	if (diff < 60) return '刚刚';
	if (diff < 3600) return `${Math.floor(diff / 60)}分钟前`;
	if (diff < 86400) return `${Math.floor(diff / 3600)}小时前`;
	if (diff < 172800) return '昨天';
	return new Date(timestamp).toLocaleDateString().replace(/\//g, '-');
};

// 页面交互方法
const handleBack = () => router.back();
const handleClickAuthor = (userId) => {
	navigationUtils.openUserInfo(userId);
};
const handleShare = () => console.log('分享功能开发中');

// 交易状态文本
const getTradeStatusText = (status) => {
	const statusMap = {
		'available': '可购买',
		'reserved': '已预订',
		'sold': '已售出'
	};
	return statusMap[status] || '未知';
};

// 交易状态类型
const getTradeStatusType = (status) => {
	const typeMap = {
		'available': 'success',
		'reserved': 'warning',
		'sold': 'info'
	};
	return typeMap[status] || 'info';
};

// 求助状态文本
const getHelpStatusText = (status) => {
	const statusMap = {
		'pending': '待解决',
		'in_progress': '进行中',
		'resolved': '已解决'
	};
	return statusMap[status] || '未知';
};

// 求助状态类型
const getHelpStatusType = (status) => {
	const typeMap = {
		'pending': 'error',
		'in_progress': 'warning',
		'resolved': 'success'
	};
	return typeMap[status] || 'info';
};

// 联系卖家/求助者
const handleContact = () => {
	uni.showModal({
		title: '联系方式',
		content: post.value.contactInfo || '暂无联系方式',
		showCancel: false
	});
};

// 我来帮忙
const handleHelp = () => {
	uni.showModal({
		title: '联系求助者',
		content: `联系方式：${post.value.contactInfo || '暂无'}`,
		confirmText: '好的',
		success: (res) => {
			if (res.confirm) {
				showToast('请通过联系方式与TA沟通', 'none');
			}
		}
	});
};

// 下载附件
const handleDownload = (file) => {
	showToast('下载功能开发中', 'none');
	console.log('下载文件:', file);
};

const handleLike = async () => {
	// 检查登录状态
	const token = uni.getStorageSync('token');
	if (!token) {
		showToast('请先登录', 'none');
		setTimeout(() => {
			uni.navigateTo({
				url: '/pages/login/login'
			});
		}, 1000);
		return;
	}

	try {
		const newState = !isLiked.value;

		// 调用 Mock API
		if (newState) {
			await mockLikePost(post.value.postId);
		} else {
			await mockUnlikePost(post.value.postId);
		}

		isLiked.value = newState;
		post.value.likeCount = newState ? (post.value.likeCount || 0) + 1 : (post.value.likeCount || 0) - 1;

		showToast(newState ? '点赞成功' : '取消点赞', 'success');
	} catch (error) {
		console.error('点赞失败:', error);
		showToast('操作失败', 'error');
	}
};
const handleCollect = async () => {
	// 检查登录状态
	const token = uni.getStorageSync('token');
	if (!token) {
		showToast('请先登录', 'none');
		setTimeout(() => {
			uni.navigateTo({
				url: '/pages/login/login'
			});
		}, 1000);
		return;
	}

	try {
		const newState = !isCollected.value;

		// 调用 Mock API
		if (newState) {
			await mockCollectPost(post.value.postId);
		} else {
			await mockUncollectPost(post.value.postId);
		}

		isCollected.value = newState;
		post.value.collectCount = newState ? (post.value.collectCount || 0) + 1 : (post.value.collectCount || 0) - 1;

		showToast(newState ? '收藏成功' : '取消收藏', 'success');
	} catch (error) {
		console.error('收藏失败:', error);
		showToast('操作失败', 'error');
	}
};
const handleFollow = async () => {
	try {
		const newState = !isFollowed.value;
		isFollowed.value = newState;
	} catch (error) {
		isFollowed.value = !isFollowed.value;
		console.error('关注失败:', error);
	}
};
const scrollToComment = () => commentComponent.value?.scrollToComment();
</script>

<style lang="scss" scoped>
@import './styles/post-info.scss';
.post-container {
	padding-bottom: 120rpx;
}

// 新增样式：板块标签
.post-badges {
	display: flex;
	gap: 16rpx;
	margin: 16rpx 0;
	flex-wrap: wrap;
}

// 新增样式：信息区块
.trade-info,
.help-info,
.lost-found-info {
	margin-top: 32rpx;
	padding: 24rpx;
	background: #f8f9fa;
	border-radius: 16rpx;

	.info-section {
		.info-title {
			font-size: 32rpx;
			font-weight: 600;
			color: #333;
			margin-bottom: 24rpx;
		}

		.info-row {
			display: flex;
			align-items: center;
			margin-bottom: 16rpx;

			.info-label {
				font-size: 28rpx;
				color: #666;
				min-width: 140rpx;
			}

			.info-value {
				font-size: 28rpx;
				color: #333;
				flex: 1;

				&.price {
					font-size: 36rpx;
					font-weight: 600;
					color: #ff4d4f;
				}
			}
		}
	}

	.contact-btn {
		margin-top: 24rpx;
	}
}

// 新增样式：附件列表
.attachments {
	margin-top: 32rpx;

	.info-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
		margin-bottom: 16rpx;
	}

	.attachment-list {
		.attachment-item {
			display: flex;
			align-items: center;
			padding: 24rpx;
			background: #f8f9fa;
			border-radius: 12rpx;
			margin-bottom: 16rpx;

			.file-info {
				flex: 1;
				margin-left: 16rpx;

				.file-name {
					display: block;
					font-size: 28rpx;
					color: #333;
					margin-bottom: 8rpx;
				}

				.file-size {
					display: block;
					font-size: 24rpx;
					color: #999;
				}
			}
		}
	}
}
</style>
